package com.bezdelnick.forum.dao.hibernate;

import com.bezdelnick.forum.dao.IAppUserDao;
import com.bezdelnick.forum.domain.AppUser;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 17.08.12
 * Time: 15:22
 * To change this template use File | Settings | File Templates.
 */
public class AppUserDaoImpl implements IAppUserDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppUserDaoImpl.class);

    @Autowired(required = true)
    private SessionFactory sessionFactory;

    @Override
    public List<AppUser> loadUsers() {
        Session session = null;
        List<AppUser> appUsers = null;
        try {
            session = sessionFactory.openSession();

            String hql =
                    "select user " +
                            "from AppUser user, UserRole role " +
                            "where " +
                            "user.id = role.userId and " +
                            "role.authority = 'USER'";

            Query query = session.createQuery(hql);
            appUsers = (List<AppUser>) query.list();

            return appUsers;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public List<AppUser> loadAdmins() {
        Session session = null;
        List<AppUser> appUsers = null;
        try {
            session = sessionFactory.openSession();

            String hql =
                    "select user " +
                            "from AppUser user, UserRole role " +
                            "where " +
                            "user.id = role.userId and " +
                            "role.authority = 'ADMIN'";

            Query query = session.createQuery(hql);
            appUsers = (List<AppUser>) query.list();

            return appUsers;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public List<AppUser> loadAdminsWithoutEnabled() {
        Session session = null;
        List<AppUser> appUsers = null;
        try {
            session = sessionFactory.openSession();

            String hql =
                    "select user " +
                            "from AppUser user, UserRole role " +
                            "where " +
                            "user.id = role.userId and " +
                            "user.enabled = 0 and " +
                            "role.authority = 'ADMIN'";

            Query query = session.createQuery(hql);
            appUsers = (List<AppUser>) query.list();

            return appUsers;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public AppUser getUserById(long id) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            return (AppUser) session.get(AppUser.class, id);
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public AppUser getUserByName(String name) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            AppUser appUser = (AppUser) session.createCriteria(AppUser.class).add(Property.forName("username").eq(name)).list().get(0);
            return appUser;
        } catch (Exception ex) {
            LOGGER.warn(ex.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public boolean insertUser(AppUser appUser) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            session.save(appUser);
            return true;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return false;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public boolean updateUser(AppUser appUser) {
        Session session = null;
        try {
            session = sessionFactory.openSession();

            String hql =
                    "update AppUser user " +
                            "set " +
                            "username= :username, " +
                            "email= :email, " +
                            "password= :password, " +
                            "enabled= :enabled " +
                            "where id= :id";

            Query query = session.createQuery(hql);
            query.setString("username", appUser.getUsername());
            query.setString("email", appUser.getEmail());
            query.setString("password", appUser.getPassword());
            query.setBoolean("enabled", appUser.isEnabled());
            query.setLong("id", appUser.getId());
            query.executeUpdate();

            //session.update(question);
            return true;
        } catch (Error e) {
            LOGGER.error(e.getMessage());
            return false;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }
}
